// Created by liusc on 2020/8/5-9:24.
import { getDict } from "~/utils";
import uploadMedia from '@/components/upload-media'
import { getItem2, getObj, putObj3,startBudgetAmend } from "@/views/wy-budget/api/budgetapply.js";
import { getFiles, checkFiles, delFiles } from "@/views/wy-budget/api/fileoperation.js";
import Budget from '@/assets/vue-mixin/budget'
import { formatMoney } from '@/utils'

export default {
    name: "apply_edit",
    mixins: [Budget],
    components: { uploadMedia },

    data () {

        var doubleValidate = (rule, value, callback) => {
            let reg = /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/;
            let lable = rule.message;
            if (!reg.test(value)) {
                return callback(new Error("数值格式错误"));
            } else {
                callback();
            }
        };

        return {
            isShow: false,
            fileUploadUrl: '/admin/sys-file/upLodeFileEdit',
            uploadFileList: [],
            fileList: [],
            modelType: 'budgetApply',
            isEdit: true,
            busId: '',

            form: {
                applyData: {
                    applyId: '',
                    budgetId: '',
                    budgetCode: '',
                    applyName: '',
                    applyDept: '',
                    applyType: '',
                    budgetSum: '',
                    budgetSum2: '',
                    changeAmount: '',
                    remarks: '',
                    fileId: '',
                },
                itemValueList: [],
                operateType: '',
            },

            rules: {
                applyData: {
                    budgetSum: [
                        { required: true, message: '请输入预算总金额', trigger: 'blur' },
                        { validator: doubleValidate, trigger: "blur" },
                    ],
                    budgetSum2: [
                        { required: true, message: '请输入预算总金额', trigger: 'blur' },
                        { validator: doubleValidate, trigger: "blur" },
                    ],
                    changeAmount: [
                        { required: true, message: '请输入预算总金额', trigger: 'blur' },
                        { validator: doubleValidate, trigger: "blur" },
                    ],
                    remarks: [
                        { required: true, message: '请输入备注', trigger: 'blur' },
                        { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
                    ],
                },
            }
        }
    },

    computed: {
        applyDept2: function () {
            let types = getDict('budget_department')
            let pv = this.form.applyData.applyDept
            if (pv && types.length > 0) {
                const pts = types.filter(t => t.value == pv)
                return pts ? pts[0].label : ''
            }
            return ''
        },

        applyType2: function () {
            let types = getDict('budget_type')
            let pv = this.form.applyData.applyType
            if (pv && types.length > 0) {
                const pts = types.filter(t => t.value == pv)
                return pts ? pts[0].label : ''
            }
            return ''
        },
    },

    mounted () {
    },

    created () {
        const loading = this.$loading({
            lock: true,
            text: '数据加载中'
        });

        setTimeout(() => {
            getObj(this.$route.params.applyId).then(respData => {
                this.$refs['add-form'].resetFields()
                this.form.applyData = respData.data.data
                this.initItem(this.form.applyData.applyId);

                this.busId2 = respData.data.data.applyFileId
                this.$refs.myApply2.getFiles(this.busId2)

                this.busId = this.form.applyData.fileId
                if (this.busId) {
                    this.isEdit = false
                    getFiles(this.busId, this.modelType).then(rep => {
                        this.fileList = rep.data.data
                        loading.close()
                    }).catch(e => {
                        loading.close()
                    })
                } else {
                    loading.close()
                }
            }).catch(e => {
                loading.close()
                this.$message({
                    type: 'error',
                    message: '数据获取失败!'
                })
            })
        }, 200)
    },

    methods: {
        // 科目
        initItem () {
            getItem2(this.form.applyData.applyId).then(rep => {
                let rspD = rep.data.data
                if (rspD) {
                    rspD = rspD.map((rs, index) => {
                        rs['sortNum'] = index + 1
                        return rs
                    })
                }
                this.form.itemValueList = rspD
            })
        },

        // 取消
        cancel () {
            this.closeNowRouter()
        },

        // 保存提交
        commit () {
            this.form.operateType = '2'
            this.checkWillBe() && this.$refs['add-form'].validate(valid => {
                if (valid) {
                    if (this.uploadFileList.length > 0) {
                        if (!this.isEdit) {
                            this.$refs.myApply.submit(this.modelType, this.busId);
                        } else {
                            this.$refs.myApply.submit(this.modelType);
                        }
                    } else {
                        this.$alert('请上传附件');
                        return
                    }
                }
            })
        },

        sendFormData (val) {
            if (val && this.isEdit) {
                this.form.applyData.fileId = val
                this.busId = val
                this.isEdit = false
            }


            putObj3(this.form).then((rep) => {

                getObj(this.$route.params.applyId).then(respData => {
                    startBudgetAmend(respData.data.data).then(respData => {
                    }).catch(e => {
                    });
                }).catch(e => {
                });

                this.success_message("修改成功");
                this.closeNowRouter();
            }).catch((e) => {
                this.errormessage("修改失败");
            })
        },

        success_message (msg) {
            this.$message({
                type: "success",
                message: msg,
            });
        },

        errormessage (msg) {
            this.$message({
                type: "error",
                message: msg,
            });
        },

        closeNowRouter () {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            //跳转
            this.$router.push({ name: 'amendapply_list' })
        },

        onSuccess (rep, file, fileList) {
            //文件上传成功，开始保存表单
            //this.loadClose()
            if (rep.data != null) {
                this.sendFormData(rep.data)
            } else {
                this.err('提交失败')
            }
        },

        onError (err, file, fileList) {
            //this.loadClose()
            this.err('提交失败')
        },

        beforeUpload () {
            //this.loadAction('请稍等...')
        },

        handleClean (file) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delFiles(file.fileId, this.modelType).then(resp => {
                    if (resp.data.code === 0) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        //this.fileList = []
                        this.fileList = this.fileList.filter(file => file.fileId != fileId)
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败!'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
    }
}
